package com.ht.medicaltreatment.activity

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.SystemClock
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.SampleListAdapter
import com.ht.medicaltreatment.bean.SampleListPage
import com.ht.medicaltreatment.utils.NFCUtils
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.UIDUitls
import com.ht.medicaltreatment.viewmodel.SampleViewModl
import kotlinx.android.synthetic.main.activity_search_sample_layout.etSearch
import kotlinx.android.synthetic.main.activity_search_sample_layout.includeScan
import kotlinx.android.synthetic.main.activity_search_sample_layout.llNFC
import kotlinx.android.synthetic.main.activity_search_sample_layout.llScan
import kotlinx.android.synthetic.main.activity_search_sample_layout.recyclerView
import kotlinx.android.synthetic.main.activity_search_sample_layout.refreshLayout
import kotlinx.android.synthetic.main.include_scan_layout.btnBack

/**
 * 搜索样本
 */
class SearchSampleActivity:BaseActivity(), OnItemClickListener, View.OnClickListener {
    override fun getLayoutId() = R.layout.activity_search_sample_layout

    private var isNFC = false
    private lateinit var mModel: SampleViewModl
    private var page = 1
    private var name = ""
    private var uid = ""
    private lateinit var adapter: SampleListAdapter
    private var clickTime = 1L
    private var isJump = false
    private var barCode = ""

    override fun init() {
        setTitle("搜索结果页")
        mModel = ViewModelProvider(this)[SampleViewModl::class.java]
        uid = intent.getStringExtra("uid")?:""
        barCode = intent.getStringExtra("barCode")?:""

        if(Build.MODEL == "V9100"){
            ScanUtils.init()
        }else{
            isNFC = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC)
            if(isNFC) NFCUtils(this)
        }
        etSearch.requestFocus()
        adapter = SampleListAdapter()
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter
        adapter.setOnItemClickListener(this)

        llNFC.setOnClickListener(this)
        llScan.setOnClickListener(this)
        btnBack.setOnClickListener(this)

        refreshLayout.setOnLoadMoreListener {
            page++
            initData()
        }
        initData()

        etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener{
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                val currentTime = SystemClock.currentThreadTimeMillis()
                val t = currentTime - clickTime
                if(t > 100){
                    clickTime = currentTime
                    name = v!!.text.toString()
                    name = name.trim()
                    if(TextUtils.isEmpty(name)) {
                        name = ""
                    }
                    uid = ""
                    initData()
                    return true
                }
                return false
            }
        })
    }

    override fun onClick(v: View?) {
        when(v){
            //NFC
            llNFC -> {
                isJump = false
                includeScan.visibility = View.VISIBLE
                ScanUtils.open {
                    ScanUtils.close()
                    if(isJump){
                        return@open
                    }
                    isJump = true
                    includeScan.visibility = View.GONE
                    uid = it
                    name = ""
                    barCode = ""
                    initData()
                }
            }

            //二维码扫描
            llScan -> {
                startActivityForResult(ScanZBarActivity::class.java){
                    barCode = it?.getStringExtra("resultUid")?:""
                    uid = ""
                    name = ""
                    initData()
                }
            }

            btnBack -> {
                includeScan.visibility = View.GONE
                ScanUtils.close()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if(!isNFC)return
        //开启前台调度系统
        NFCUtils.mNfcAdapter.enableForegroundDispatch(this, NFCUtils.mPendingIntent, NFCUtils.mIntentFilter,
            NFCUtils.mTechList)
    }

    override fun onPause() {
        super.onPause()
        if(!isNFC)return
        //关闭前台调度系统
        NFCUtils.mNfcAdapter.disableForegroundDispatch(this)
    }

    fun initData(){
        showProgress()
        name = etSearch.text.toString()
        mModel.sampleList(page,name,uid,barCode,{
            dismissProgress()
            if(page > 1){
                adapter.addData(it.rows)
                refreshLayout.finishLoadMore()
            }else{
                adapter.setNewInstance(it.rows)
            }
        })
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if(!isNFC)return
        //当该Activity接收到NFC标签时，运行该方法
        //调用工具方法，读取NFC数据
        uid = NFCUtils.readNFCId(intent)
        uid = UIDUitls.sort(uid)

    }

    override fun onDestroy() {
        super.onDestroy()
        ScanUtils.onDestroy()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = adapter.getItem(position) as SampleListPage
        val intent = Intent(this,SampleUpdateActivity::class.java)
        intent.putExtra("id",item.id)
        startActivity(intent)
    }
}